package com.wetao.lib_common.base;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.AttributeSet;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.wetao.lib_common.R;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.DialogXUtil;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.StringUtil;

import butterknife.ButterKnife;

public abstract class BaseActivity<V extends BaseViewImp, P extends BasePresenter<V>> extends RxAppCompatActivity {

    private PowerManager.WakeLock wakeLock = null;
    private boolean mIsBindTsdService = false;
    protected TsdService.LocalBinder mTsdServiceBinder;
    protected TsdService mTsdService = null;
    private String mClassName = null;
    private TsdService.OnDataReceiveListener mTsdServiceListener;



    //引用V层和P层
    private P presenter;
    private V view;

    protected TextView tv_title;
    protected ImageView iv_back;

    protected Gson gson;

    public P getPresenter() {
        return presenter;
    }

    private final ServiceConnection mTsdServiceConnection = new ServiceConnection() {
        public void onServiceConnected(final ComponentName className, IBinder rawBinder) {
            mTsdServiceBinder = (TsdService.LocalBinder) rawBinder;
            mTsdService = mTsdServiceBinder.getService();
            LogUtils.i("m1: onServiceConnected");

            mTsdService.setOnDataReceiveListener(mTsdServiceListener);

            setTsdServiceTag(mClassName);
            setTsdServiceConnected();
            LogUtils.i("m1:onServiceConnected mService= " + mTsdService);
        }

        public void onServiceDisconnected(ComponentName classname) {
            mTsdService = null;
        }
    };

    @Override
    protected final void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            requestWindowFeature(Window.FEATURE_NO_TITLE);
        } else {
            supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        }
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
//                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        //gson = new Gson();
        gson = new GsonBuilder().disableHtmlEscaping().create();
        setImmersionBar();
        setContentView(getLayoutId());
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); // 禁止所有的activity竖屏
        ARouter.getInstance().inject(this);
        ButterKnife.bind(this);


        if (presenter == null) {
            presenter = createPresenter();
        }
        if (view == null) {
            view = createView();
        }
        if (presenter != null && view != null) {
            presenter.attachView(view);
        }

        mClassName = this.getClass().getName();
        mIsBindTsdService = getIsBindTsdService();
        mTsdServiceListener = getTsdServiceDataReceiveListener();

        if(!ComUtil.isServiceRunning(this, TsdService.class.getName())) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(new Intent(this, TsdService.class));
            } else {
                startService(new Intent(this, TsdService.class));
            }
        }
        init();
    }

    @Override
    public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
        return super.onCreateView(parent, name, context, attrs);
    }

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        return super.onCreateView(name, context, attrs);
    }

    /**
     *初始化标题栏
     */
    protected void initTitleLayout() {
        tv_title = this.findViewById(R.id.tv_title);
        iv_back = this.findViewById(R.id.iv_back);
    }


    /**
     * 设置header标题
     * @param title
     */
    protected void setTvTitle(String title,boolean visible)
    {
        tv_title.setText(StringUtil.replaceAmp(title));
        iv_back.setVisibility(visible? View.VISIBLE:View.GONE);
    }

    //由子类指定具体类型
    public abstract int getLayoutId();

    public abstract P createPresenter();

    public abstract V createView();

    public abstract void init();

    public abstract boolean getIsBindTsdService();

    public abstract TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener();



    //设置沉浸式状态栏背景颜色，
    public void setImmersionBar() {
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarColor(R.color.bar_color)
                .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
                .init();
        //另外设置颜色，覆盖这个函数，设置下面这句代码，再去设置
        //ImmersionBar.with(this).reset();
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.i("m1: onResume");
        if(mIsBindTsdService) {
            onBindTsdService();
        }

        //出现报错时重启后台没有主界面
        /*if(!ComUtil.checkActivity(this, "com.sunducation.wts.penbox.activity", "HomeActivity")){
            onUnBindTsdService();
            stopService(new Intent(this, TsdService.class));
            finish();
        }*/
    }

    @Override
    protected void onPause() {
        LogUtils.i("m1: onPause");
        if(mIsBindTsdService) {
            onUnBindTsdService();
        }
        super.onPause();
    }

    private void onBindTsdService() {
        //acquireWakeLock();
        Intent gattServiceIntent = new Intent(this, TsdService.class);
        boolean bBind = bindService(gattServiceIntent, mTsdServiceConnection, BIND_AUTO_CREATE);
    }

    private void onUnBindTsdService() {
        //releaseWakeLock();
        setTsdServiceDisConnect();
        setTsdServiceTag(null);
        if(mTsdService != null) {
            mTsdService.setOnDataReceiveListener(null);
        }
        unbindService(mTsdServiceConnection);
        mTsdService = null;
        mTsdServiceBinder = null;
    }

    private void setTsdServiceTag(String className) {
        if(mTsdServiceBinder != null) {
            mTsdServiceBinder.setTsdServiceTag(className);
        }
    }

    public void setTsdServiceConnected() {
        if(mTsdServiceBinder != null) {
            mTsdServiceBinder.setTsdServiceConnected();
        }
    }

    public void setTsdServiceDisConnect() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.detachView();
        }

        DialogXUtil.releaseDialog();

    }

    //设置字体为默认大小，不随系统字体大小改而改变
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if (newConfig.fontScale != 1)//非默认值
            getResources();
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        if (res.getConfiguration().fontScale != 1) {//非默认值
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults();//设置默认
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
        }
        return res;
    }

    /**
     * 获取电源锁，保持该服务在屏幕熄灭时仍然获取CPU时，保持运行
     */
    protected void acquireWakeLock() {
        if (null == wakeLock) {
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                    | PowerManager.ON_AFTER_RELEASE, getClass()
                    .getCanonicalName());
            if (null != wakeLock && !wakeLock.isHeld()) {
                LogUtils.i("m1:call acquireWakeLock");
                wakeLock.acquire();
            }
        }
    }

    // 释放设备电源锁
    protected void releaseWakeLock() {
        if (null != wakeLock && wakeLock.isHeld()) {
            LogUtils.i("m1:call releaseWakeLock");
            wakeLock.release();
            wakeLock = null;
        }
    }
}
